package com.xiaotu.storage.converter;

import com.xiaotu.common.util.RegexUtils;
import org.springframework.stereotype.Component;

import com.xiaotu.common.exception.SpiderException;
import com.xiaotu.common.exception.SpiderExceptionCode;
import com.xiaotu.common.util.SepratorUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @类名 StringArrayConverter
 * @日期 2017年4月17日
 * @作者 高海军
 * @功能
 */
@Component("StringArrayConverter")
public class StringArrayConverter extends AConverter
{

    @Override
    protected Object doConvert(String value, JSONObject target,
            boolean needThrow)
    {
        JSONArray array = null;
        try
        {
            array = RegexUtils.regexMatch("\\[(.+)\\]", value) ? JSONArray.fromObject(value) :
                    JSONArray.fromObject(value.split(SepratorUtil.SEP_COMMA_EN));
        }
        catch (Exception e)
        {
            if (needThrow)
                throw new SpiderException(SpiderExceptionCode.DataInvalideException, e);
        }
        if (array == null || array.isEmpty())
            return null;
        StringBuffer buffer = new StringBuffer();
        for (Object obj : array)
        {
            if (obj == null)
                continue;
            buffer.append(SepratorUtil.SEP_COMMA_EN + "\"" + this.getItemValue(obj, target,
                    needThrow) + "\"");
        }
        if (buffer.length() < 1)
            return null;

        return "{" + buffer.substring(SepratorUtil.SEP_COMMA_EN.length()) + "}";
    }

    protected Object getItemValue(Object obj, JSONObject target, boolean needThrow)
    {
        return obj.toString();
    }

}
